package eleanor.ltd.isRealEstate.pages.user;

import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.corelib.components.Form;
import org.apache.tapestry5.ioc.annotations.Inject;

import eleanor.ltd.isRealEstate.dao.user.UserDAO;
import eleanor.ltd.isRealEstate.entities.user.User;
import eleanor.ltd.isRealEstate.pages.Index;

public class EditUser {

	@Property
	@Persist
	private User user;
	
	@Inject
	private UserDAO userDAO;
	
	@Property
	private String newPassword;
	
	@Property
	private String newEmail;
	
	@Component
	private Form editForm;
	
	Object onActivate(Long id) {
		user = userDAO.findByID(id);
		if (user == null) {
			return BrowseUser.class;
		}
		return null;
	}

	Object onSubmitFromEditForm() {
		try {
			if (newPassword != null) {
				user.setPassword(newPassword);
			}
			if (!newEmail.equals(user.getEmailAddress())) {
				user.setEmailAddress(newEmail);
			}
			userDAO.update(user);
			return BrowseUser.class;
		} catch (Exception e) {
			return Index.class;
		}

	}
}
